package com.cloud.config.security;
 
import com.alibaba.fastjson.JSON;
import com.cloud.utils.ResponseUtil;
import com.cloud.config.jwt.JwtTokenUtil;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class IanAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    
    @Value("${jwt.expiration}")
    private Long expiration;//有效期

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
			response.setHeader("Content-Type", "application/json;charset=utf-8");
			UserDetails userDetails = (UserDetails) authentication.getPrincipal();
			String jwtToken = jwtTokenUtil.generateToken(userDetails);
			jwtTokenUtil.setExpire(jwtToken,userDetails.getUsername(),expiration+100000);
			response.getWriter().write(JSON.toJSONString(ResponseUtil.ok("登录成功", jwtToken)));
			response.getWriter().flush();
	}
    
    
}